package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        long daysBetween = ChronoUnit.DAYS.between(begin, end);
        if (daysBetween > 90) {
            throw new IllegalArgumentException("查询时间范围不能超过90天");
        }
        // 1.datalist计算出来
        List<LocalDate> dateList = new ArrayList<>();// 开始日期到结束日期的日期列表
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);// 日期加1
            dateList.add(begin);
        }
        // 2.turnoverList计算出来
        List<Double> turnoverList = new ArrayList<>();
        Map map = new HashMap();
        for(LocalDate date : dateList){
            LocalDateTime beginDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("begin", beginDateTime);
            map.put("end", endDateTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//  如果为null则赋值为0.0
            turnoverList.add(turnover);
        }
        // 3.封装成TurnoverReportVO并返回
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();


    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 查询日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 查询用户数据
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : dateList){
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            // 查询总用户
            Integer totalUser = userMapper.countByMap(map);
            // 查询新增用户
            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
// 封装返回
        return UserReportVO.builder()
                           .dateList(StringUtils.join(dateList, ","))
                           .totalUserList(StringUtils.join(totalUserList, ","))
                           .newUserList(StringUtils.join(newUserList, ","))
                           .build();
    }

    /**
     * 指定时间内订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        log.info("订单数据统计：{}到{}", begin, end);
        // 查询日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放每天的订单数量
        List< Integer> totalOrderCountList = new ArrayList<>();
        // 存放每天的有效订单数量
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : dateList){
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询每天的订单总数
            Integer totalOrderCount = getOrderCount(beginTime, endTime, null);
            //查询每天的有效订单数量
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //添加到集合中
            totalOrderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        }

        //计算时间区间内的订单总数量
        Integer totalOrderCount = totalOrderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0)  orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;

        //封装返回
        return OrderReportVO.builder()
                           .dateList(StringUtils.join(dateList, ","))
                           .orderCountList(StringUtils.join(totalOrderCountList, ","))
                           .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                           .totalOrderCount(totalOrderCount)
                           .validOrderCount(validOrderCount)
                           .orderCompletionRate(orderCompletionRate)
                           .build();

    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        log.info("查询{}到{}的销量排名", begin, end);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        // 将List<GoodsSalesDTO> 转换成两个List
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        // 封装返回
        return SalesTop10ReportVO.builder()
                                 .nameList(StringUtils.join(names, ","))
                                 .numberList(StringUtils.join(numbers, ","))
                                 .build();
    }

    /**
     * 导出营业数据
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        log.info("导出营业数据");
        LocalDate  dateBegin = LocalDate.now().minusDays(30);
        LocalDate  dateEnd = LocalDate.now().minusDays(1);
        // 1.查询所有订单,获取30天营业数据（概览数据和明细数据）
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX)); //LocalDateTime.of()可以将LocalDate转换为LocalDateTime
        // 2.poi写入数据到excel文件并下载
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/businessData.xlsx");
        try  {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 填充数据
            XSSFSheet sheet = excel.getSheet("sheet1");//  获取第一个sheet页
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);// 时间

            //获取第四行的单元格对象
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());// 营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//  订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());//  新增用户数

            // 获得第五行的单元格对象
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount().toString());//  有效订单数
            row.getCell(4).setCellValue(businessData.getUnitPrice());//  平均客单价

            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天天的订单数据
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());// 日期
                row.getCell(2).setCellValue(data.getTurnover());// 营业额
                row.getCell(3).setCellValue(data.getValidOrderCount());//  有效订单数
                row.getCell(4).setCellValue(data.getOrderCompletionRate());//  订单完成率
                row.getCell(5).setCellValue(data.getUnitPrice());//  平均客单价
                row.getCell(6).setCellValue(data.getNewUsers());//  新增用户数
            }

            // 3.输出流下载文件到本地，response为HttpServletResponse对象,用于 设置响应头信息，实现文件下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 关闭资源
            out.close();
            excel.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 查询指定时间区间内订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }


}
